//  Depends: modal.js
//  Depends: settings.js
//  Depends: bookdb.js (database-websql.js)

$(document).bind("mobileinit", function(){
  //apply overrides here
});

var _settings = null;
var _bookDb = null;
var _initQueue = null;
var $_initList = null;

function loadingStatus(text, value)
{
  return '<li>'+ text + '<span class="ui-li-count">' + value + '</span></li>';
}

$(function() {
  // Setup
  _settings = new Settings();
  _settings.init();

  $_initList = $('div#loading ul');

  // Build Init Queue
  _initQueue = $.Deferred().done(function() {
    // Show loading page
    $.mobile.changePage('#loading');
  }).done(function() {
    // Then init BookDB (websql version)
    _bookDb = new BookDatabaseWebSql();
    _bookDb.init();
  }).fail(function() {
    $_initList.append(loadingStatus('Init Database', 'fail'));
  }).done(function() {
    $_initList.append(loadingStatus('Init Database', 'ok'));
    if (_settings.lastImportTime == '') {
      _initQueue.reject();
    } else {
      _initQueue.resolve();
    }
  }).done(function() {
    $_initList.append(loadingStatus('Check for Book XML', 'ok'));
  }).fail(function() {
    $_initList.append(loadingStatus('Check for Book XML', 'loading'));
    ImportXml();
  }).done(function() {
    $_initList.append(loadingStatus('Import XML', 'ok'));
  }).fail(function() {
    $_initList.append(loadingStatus('Import XML', 'fail'));
  });



  // EVENT: SETTINGS - SAVE CLICK
  $(' a#settings-save').click(function() {
    _settings.importType = $('div#settings select#bookXmlType').val();
    _settings.importUrl = $('div#settings input#bookXmlUrl').val();
    _settings.save();
  });

  // EVENT: SETTINGS - BEFORE SHOW
  $('div#settings').live('pagebeforeshow', function(event, ui){
    $('div#settings select#bookXmlType').val(_settings.importType);
    $('div#settings input#bookXmlUrl').val(_settings.importUrl);
    $('div#settings input#lastImportedURL').val(_settings.lastImportUrl);
    $('div#settings input#lastImportedTime').val(_settings.lastImportTime);
  });

  // EVENT: SETTINGS - REIMPORT
  $('div#settings a#reimportUrl').live('click', function(event, ui){
    _settings.lastImportUrl = '';
    _settings.lastImportTime = '';
    _settings.save();
    ImportXml(); //TODO: I think I want to do this by redirecting to the splash and have a check as part of the spash
  });

  // EVENT: SPLASH - SHOW
  $('div#splash').live('pageshow', function(event, ui) {
    // Start Queue
    _initQueue.resolve();
  });

  // EVENT: LOADING - SHOW
  $('div#loading').live('pageshow', function(event, ui) {
  });

  // EVENT: TAGS - SHOW
  $('div#tags').live('pageshow', function(event, ui) {
    var $list = $(this).find('ul');
    var tags = _bookDb.allTags(function(tags) { 
      var letter = '';
      for (var idx in tags) {
        var tag = tags[idx];
        if (letter != tag.charAt(0).toUpperCase()) {
          letter = tag.charAt(0).toUpperCase();
          $list.append('<li data-role="list-divider">' + letter + '</li>');
        }
        $list.append('<li><a href="#">' + tag + '</a></li>');
        //$('div#tags').page(); // Reinit jQuery.Mobile page
        $list.listview('refresh');
      }
    });
  });

  // EVENT: TAGS - HIDE
  $('div#tags').live('pagehide', function(event, ui) {
    var $list = $(this).find('ul');
    $list.html('');  // Clear out all HTML
  });
});




function ImportXml()
{
  //TODO: Need to check if we need to import, this will be done by checking if teh last import fields are set
  
  if (_settings.importType == 'calibre-xml') {
    $.ajax({
      type: "GET",
      url: _settings.importUrl,
      dataType: "xml",
      success: function(data, textStatus, jqXHR)
      {
        _bookDb.clear();  // Wipe database
        $(data).find('record').each(function() {
          var book = new Book();
          book.uuid = $(this).find('uuid').text();
          book.publisher = $(this).find('publisher').text();
          book.rating = $(this).find('rating').text();
          book.isbn = $(this).find('isbn').text();
          book.title = $(this).find('title').text();
          $(this).find('authors author').each(function() { book.authors.push($(this).text()) }); 
          $(this).find('tags tag').each(function() { book.tags.push($(this).text()) }); 
          book.comments = $(this).find('comments').text();
          book.series = $(this).find('series').text();
          book.seriesIndex = $(this).find('series').attr('index');

          _bookDb.savebook(book);
        });
      },
      error: function(jqXHR, textStatus, errorThrown)
    {
      alert('Error Importing URL. Please check Options to insure they are correct and reload if needed.')
    },
    complete: function(jqXHR, textStatus)
    {
      alert('Done importing URL.');
    }
    });
  } 
  else {
    alert('ERROR: Unknown Import Type.')
  }
}